package nuc.jyg.controller;

import nuc.jyg.dto.AppointExecution;
import nuc.jyg.dto.Result;
import nuc.jyg.entity.Book;
import nuc.jyg.exception.AppointException;
import nuc.jyg.exception.NoNumberException;
import nuc.jyg.exception.RepeatAppointException;
import nuc.jyg.service.BookService;
import nuc.jyg.util.AppointmentStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author Nuc YongGuang Ji
 * Created by JiYongGuang on 2017/5/31.
 */
@Controller
@RequestMapping("/book")  // url:/模块/资源/{id}/细分 /seckill/list
public class BookController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model) { // 这里方法是private 还是 public 没有区别。
        List<Book> bookList = bookService.getList();
        model.addAttribute("list", bookList);

        // list.jsp + model = ModelAndView
        return "list"; //  WEB-INF/jsp/list.jsp
    }

    @RequestMapping(value = "/{bookId}/detail", method = RequestMethod.GET)
    private String detail(@PathVariable Long bookId, Model model) {
        if (bookId == null) {
            return "redirect:/book/list";
        }
        Book book = bookService.getByID(bookId);
        if (book == null) {
            return "forword:/book/lista";
        }
        model.addAttribute("book", book);
        return "detail";
    }

    @RequestMapping(value = "/{bookId}/appoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    @ResponseBody
    private Result<AppointExecution> appoint(@PathVariable("bookId") Long bookId, @RequestParam("studentId") Long studentId) {
        if (studentId == null || studentId.equals("")) {
            return new Result<AppointExecution>(false, "学号不能为空");
        }
        //AppointExecution execution = bookService.appoint(bookId, studentId);//错误写法，不能统一返回，要处理异常（失败）情况
        AppointExecution appointExecution = null;

        try {
            appointExecution = bookService.appoint(bookId, studentId);
        } catch (NoNumberException e1) {
            appointExecution = new AppointExecution(bookId, AppointmentStateEnum.NO_NUMBER);
        } catch (RepeatAppointException e2) {
            appointExecution = new AppointExecution(bookId, AppointmentStateEnum.REPEAT_APPOINT);
        } catch (AppointException e) {
            appointExecution = new AppointExecution(bookId, AppointmentStateEnum.INNER_ERROR);
        }
        return new Result<AppointExecution>(true, appointExecution);
    }

}
